package com.example.taluo.logic;

import com.example.taluo.entity.dto.gamedto.GameState;
import com.example.taluo.entity.dto.gamedto.PlayerState;
import com.example.taluo.utils.GameUtils;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.Getter;
import lombok.Setter;

import java.util.ArrayList;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/*** @Author supersaiya
 * @Description 游戏房间类

 * @Date 2025/2/19 11:31

 * @Version 1.0*/
@Getter
@Setter
public class GameRoom {
    private String roomId;
    private ConcurrentHashMap<String, Channel> players; // 玩家通道映射
    private GameState gameState; // 游戏状态
    private GameLogic gameLogic; // 游戏逻辑

    public GameRoom(String roomId) {
        this.roomId = roomId;
        this.players = new ConcurrentHashMap<>();
        this.gameState = new GameState();
        this.gameLogic = new GameLogic();
    }

    public void addPlayer(String playerId, Channel channel) {
        players.put(playerId, channel);
        gameState.addPlayer(playerId, new PlayerState(playerId));
        broadcastGameState();
    }

    public void removePlayer(String playerId) {
        players.remove(playerId);
        gameState.removePlayer(playerId);
        broadcastGameState();
    }

    public void startGame() {
        System.out.println("启动游戏");
        gameLogic.initializeGame(gameState);
        broadcastGameState();
    }

    public void broadcastGameState() {
        String jsonGameState = GameUtils.objectToJson(gameState);
       // System.out.println("游戏状态是"+ jsonGameState);
        players.forEach((id, channel) -> {
            channel.writeAndFlush(new TextWebSocketFrame(jsonGameState));
        });
    }

    public GameLogic getGameLogic() {
        return gameLogic;
    }

    public GameState getGameState() {
        return gameState;
    }
}